package org.mifos.boss.ui.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.exolab.castor.mapping.Mapping;
import org.mifos.boss.application.model.UserCredentials;
import org.mifos.boss.domainmodel.CollectionSheet;
import org.mifos.boss.service.BossDeliveryServiceInterface;
import org.mifos.boss.service.helper.XMLConverter;
import org.mifos.boss.webservice.model.CenterDescription;
import org.mifos.boss.webservice.model.CollectionSheetDto;
import org.mifos.boss.webservice.model.CustomerHierarchy;
import org.mifos.boss.webservice.model.GroupDescription;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.oxm.castor.CastorMarshaller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.xml.sax.InputSource;

@Controller
@RequestMapping("/delivery")
public class BossDeliveryController extends AbstractController {
	// Chinmay
	static Logger logger = Logger.getLogger(BossDeliveryController.class);

	@Autowired
	private ServletContext servletContext;

	@Autowired
	@Qualifier("bossDeliveryService")
	private BossDeliveryServiceInterface bossDeliveryService;

	@Autowired
	private CastorMarshaller marshaller;

	@RequestMapping("/data")
	public ModelAndView retrieveCustomerHierarchy(HttpSession session) {

		// UserCredentials user =
		// (UserCredentials)session.getAttribute("currentUser");

		UserCredentials user = new UserCredentials();
		user.setJ_password("testmifos");
		user.setJ_username("officer");

		CustomerHierarchy cust = bossDeliveryService
				.retrieveCustomerHierarchy(user);

		// create center list
		List<CenterDescription> centers = cust.getCenters();
		List<String> centerList = new ArrayList<String>();
		List<String> groupList = new ArrayList<String>();
		for (CenterDescription c : centers) {
			centerList.add(c.getDisplayName());

			// for time beign add all groups from all centers here
			for (GroupDescription g : c.getGroups()) {
				groupList.add(g.getDisplayName());
			}
		}

		//
		//
		ModelAndView model = new ModelAndView();
		model.setViewName("delivery");

		// model.addAttribute("centerList", centerList);
		model.addObject("groupList", groupList);
		model.addObject("centerList", centerList);

		return model;
	}

	@RequestMapping("/fileDownload/{filename}")
	public void downloadFileasXML(@PathVariable("filename") String filename,
			Model model, HttpSession session, HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		String contextPath = request.getRealPath("/");
		filename = filename + ".xml";
		String xmfilename = contextPath + "WEB-INF\\" + filename;
		File file = new File(xmfilename);

		response.setContentType("text/xml");
		response.setContentLength((int)file.length());
		response.setHeader("Content-Disposition", "attachment; filename=\""
				+ filename + "\"");
		
		ServletOutputStream out = response.getOutputStream();

		FileInputStream fileIn = new FileInputStream(file);
		 
		byte[] outputByte = new byte[4096];
		//copy binary contect to output stream
		while(fileIn.read(outputByte, 0, 4096) != -1)
		{
			out.write(outputByte, 0, 4096);
		}
		fileIn.close();
		out.flush();
		out.close();
		
	}

	@RequestMapping("/getCollection")
	public CollectionSheet retrieveCollectionSheet(Model model,
			HttpSession session, HttpServletRequest request) throws IOException {
		/*
		 * // UserCredentials user =
		 * (UserCredentials)session.getAttribute("currentUser");
		 * 
		 * final String FILE_NAME = "test123444.xml";
		 * 
		 * File file = new File(FILE_NAME); // File f = new File(./test123.xml);
		 * System.out.println("\nfile path = " + file.getAbsolutePath());
		 * 
		 * UserCredentials user = new UserCredentials();
		 * user.setJ_password("testmifos"); user.setJ_username("officer");
		 * 
		 * Mapping mapping = new Mapping();
		 */
		// InputSource inputSource = new
		// InputSource(getClass().getResourceAsStream("/Users/stateofmind/mapping.xml"));

		// Resource r = new
		// InputSource(getClass().getResourceAsStream("/Users/stateofmind/mapping.xml"));

		// if(null != inputSource){
		// mapping.loadMapping(inputSource);
		// marshaller.setMappingLocation(inputSource);
		// }
		//

		// CollectionSheetDto collectionSheetDto =
		// bossDeliveryService.retreiveCollectionSheet(user);
		CollectionSheetDto collectionSheetDto = null;

		CollectionSheet collectionSheet = bossDeliveryService
				.collectonSheetDto2CollectionSheet(collectionSheetDto);
		bossDeliveryService.convertCollectionSheettoXML(collectionSheet,
				request);

		/*
		 * InputStream inputStream = null; try { inputStream =
		 * servletContext.getResourceAsStream
		 * ("/WEB-INF/content/somecontent.xml"); BufferedReader bufferedReader =
		 * new BufferedReader(new InputStreamReader(inputStream)); return
		 * bufferedReader.readLine(); } finally { if (inptStream != null) {
		 * inputStream.close(); } }
		 */
		/*
		 * String xmfilename = servletContext.getContextPath() +
		 * "somecontent.xml"; ApplicationContext appContext = new
		 * ClassPathXmlApplicationContext("applicationContext.xml");
		 * XMLConverter converter = (XMLConverter)
		 * appContext.getBean("XMLConverter");
		 * logger.info("Convert XML to CollectionSheet!"); //from XML to object
		 * try {
		 * 
		 * 
		 * collectionSheet =
		 * (CollectionSheet)converter.convertFromXMLToObject(xmfilename); }
		 * catch (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */
		/*
		 * // File file = new File(FILE_NAME); FileOutputStream os = null;
		 * 
		 * try { // os = new FileOutputStream(FILE_NAME); os = new
		 * FileOutputStream(file, false); marshaller.marshal(collectionSheet,
		 * new StreamResult(os));
		 * 
		 * 
		 * } catch (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); } finally{ if (os != null){ os.close(); } }
		 */
		return collectionSheet;

	}

}
